﻿/*$.extend($.fn.validatebox.defaults.rules, {
		unique:{
	        validator: function(value,param){
	        	//console.log(param);
	        	var editId=dg.data('editId');
	        	if(editId==undefined){
	        		//setTimeout('',200);
	        		return true;
	        	}
	        	//var idField=dg.datagrid('options').idField;
	        	//var id= dg.datagrid('getRows')[dg.data('editIndex')].id;
	        	var check=$.ajax({
								type: "post",
								async:false,
								contentType:"application/json",
								url: "/authenticated/ajax/boolean/"+param[0],
								data:JSON.stringify({'username':value,'id':editId}),
								dataType:"json",
								success: function(result){
									return result;
								},
								error: function(){
									return false;
								}
							}).responseText;
	        	return check=='true';
	        },
	        message: '选项已存在,请重新录入.'
	    }
});*/
$.extend($.fn.datagrid.methods, {
	cancelEditing:function(jq){
		var dg=jq;
		var editId = dg.data('editId');
		if (editId){
			var editIndex=dg.datagrid('getRowIndex',editId);
			if(editIndex){
				dg.datagrid('cancelEdit',editIndex);
			}
		}
	},
	beginEditing:function(jq,param){
		var dg=jq;
		var idField=dg.datagrid('options').idField;
		var rowid=param[idField];
		if(!rowid){
			alert("row没有主键,可能原因,没有定义idField");
		}
		var rowIndex=dg.datagrid('getRowIndex',rowid);
		if(dg.data('editId')!=rowid){
    		if(dg.datagrid('endEditing')){
    			//开始编辑
    			dg.datagrid('selectRow', rowIndex).datagrid('beginEdit', rowIndex);
				dg.data('editId',rowid);
    		}
    	}
	},
	endEditing:function(jq){
		var dg=jq;
		var editId = dg.data('editId');
		var editIndex=dg.datagrid('getRowIndex',editId);
		if (editIndex == undefined){return true;}
		if (dg.datagrid('validateRow', editIndex)){
			dg.datagrid('endEdit', editIndex);
			dg.removeData('editId');
			dg.datagrid('afterEditing');
			return true;
		} else {
			return false;
		}
	},
	afterEditing:function(jq,param){
		return jq.each(function(){
			var dg=jq;
			if(dg.datagrid('options').afterEditing){
				dg.datagrid('options').afterEditing();
			}
		});
	},
	append:function(jq,param){
		return jq.each(function(){
			var dg=jq;
			if(dg.datagrid('endEditing')){
				var length=dg.datagrid('getRows').length;
				var idField=dg.datagrid('options').idField;
				dg.datagrid('appendRow',param);//新增一行
				dg.data('editId',param[idField]);
				dg.datagrid('selectRow', length).datagrid('beginEdit',length);//编辑新增行
			}
		});
	},
	editRow:function(jq,param){
		var dg=jq;
		var selectRows=dg.datagrid('getSelections');
		if(selectRows.length>0){
			dg.datagrid('beginEditing',selectRows[0]);
		}else{
			$.messager.alert("提示", "请选择一条数据！");
		}
	},
	remove:function(jq){
		var dg=jq;
		var selectRow=dg.datagrid('getSelections');
		if(selectRow.length>0){
			$.each(selectRow,function(i,v){
				var deleteIndex=dg.datagrid('getRowIndex',v);
				dg.datagrid('deleteRow', deleteIndex);
			});
		}
	},
	getEditIndex:function(jq){
		var dg=jq;
		var editIndex=undefined;
		var editId = dg.data('editId');
		if (editId){
			editIndex=dg.datagrid('getRowIndex',editId);
		}
		return editIndex;
	},
	load:function(jq,param){
		var dg=jq;
		dg.datagrid("loading");
		var searchbar=dg.datagrid('options').toolbar;
		//var table=dg.datagrid('options').table;
		//var sqlname=dg.datagrid('options').sqlname;
		var searchForm=$(searchbar+" form");
		var searchParam=searchForm.serializeObject();
		$.extend(searchParam,dg.gridParam);
		$.post(dg.datagrid('options').loadurl,searchParam,function(result){
			dg.datagrid("loadData",result.rows);
			if(dg.pager){
				dg.datagrid('getPager').pagination('refresh',{
					total: result.total,
					pageNumber: dg.gridParam.pageNumber
				});
			}
			dg.datagrid("loaded");
		});
		
	},accept:function(jq,param){
		var dg=jq;
		//var table=dg.datagrid('options').table;
		//var sqlname=dg.datagrid('options').sqlname;
		if (dg.datagrid('endEditing')){
			var rows = dg.datagrid('getChanges');
			if (rows.length == 0) {
				$.messager.alert("提示", "没有需要提交的数据！");
				return;
			}
			var insertedRows = dg.datagrid('getChanges','inserted');
			var deletedRows  = dg.datagrid('getChanges','deleted');
			var updatedRows  = dg.datagrid('getChanges','updated');
			var params = {};
			if(insertedRows.length>0){
				params.insertedRows=insertedRows;
			}
			if(updatedRows.length>0){
				params.updatedRows=updatedRows;
			}
			if(deletedRows.length>0){
				var idArr=new Array();
				var idField=dg.datagrid('options').idField;
				$.each(deletedRows, function(i, row){
					idArr.push(row[idField]);
				});
				params.deletedRowIds=idArr;
			}
			var saveurl=dg.datagrid('options').saveurl;
			$.ajax({
				contentType:"application/json",
				url: saveurl,
				type:"POST",
				data:JSON.stringify(params),
				success: function(result){
					if(result.success){
						dg.datagrid('acceptChanges');
						dg.datagrid('load');
						$.messager.alert("提示", "保存成功！");
					}else{
						$.messager.alert("错误", result.message);
					}			
				}
			});
		}
	},showChanges:function(jq,param){
		var dg=jq;
		if (dg.datagrid('endEditing')){
			var changesRows=dg.datagrid('getChanges');
			var insertedRows = dg.datagrid('getChanges','inserted');
			var deletedRows = dg.datagrid('getChanges','deleted');
			var updatedRows = dg.datagrid('getChanges','updated');
			$.messager.alert("提示", changesRows.length+"条数据修改<br>新增"+insertedRows.length+"条,删除"+deletedRows.length+"条，更新"+updatedRows.length+"条");
		}else{
			$.messager.alert("提示", "编辑未结束！");
		}
	},getSelectedRow:function(jq,param){
		var dg=jq;
		var selectRow=dg.datagrid('getSelected');
		if(selectRow){
			return selectRow;
		}else{
			$.messager.alert("提示", $.messager.defaults.selectRow);
			return undefined;
		}
	},
	editCell: function(jq,param){},
	enableCellEditing: function(jq){},
	autoMergeCells : function (jq, fields) {},
    autoMergeCellAndCells : function (jq, fields) {}
});
Grid=function (options){
	var self = this;
	if(options.showCheckbox!=undefined&&options.showCheckbox==false){
		this.columns=[[]];
	}else{
		this.columns=[[{field:'checkbox',checkbox:true}]];
	}
	this.fun={
		field:{
			formatter:function(param){
				this.field=param;
				this.comboboxFormatter=function (value,row,index){
					return self.getComoboxValue(this.field,value);
			    };
				this.combotreeFormatter=function (value,row,index){
					return self.getCombotreeValue(this.field,value);
			    };
			}
		}
	};
	this.comboboxDatas={};
	this.combotreeDatas={};
	this.getComoboxValue=function(field,value){
		var text=value;
		$.each(self.comboboxDatas[field],function(i,v){
			if(v.code_value==value){
				text= v.code_name;
				return text;
			}
		});
		return text;
	};
	this.getCombotreeValue=function(field,value){
		var text;
		$.each(self.comboboxDatas[field],function(i,v){
			if(v.id==value){
				text= v.text;
				return text;
			}
		});
		return text;
	}
	this.onSelectPage=function(pageNumber, pageSize){
		self.grid.gridParam.pageNumber=pageNumber;
		self.grid.gridParam.pageSize=pageSize;
		self.grid.datagrid("load");
	};
	
	this.onDblClickRow=function(rowIndex,rowData){
		self.grid.datagrid('beginEditing',rowData);
	};
	this.onSortColumn=function(sort, order){
		self.grid.gridParam.sort=sort;
		self.grid.gridParam.order=order;
		self.grid.datagrid("load");
	};
	this.editRow=function(){
		self.grid.datagrid('editRow');
	};
	this.accept=function(){
		self.grid.datagrid('accept');
	};
	this.cancelEditing=function(){
		self.grid.datagrid('cancelEditing');
	};
	this.endEditing=function(){
		self.grid.datagrid('endEditing');
	};
	this.rejectChanges=function(){
		self.grid.datagrid('rejectChanges');
	};
	this.remove=function(){
		self.grid.datagrid('remove');
	};
	this.load= function(){
		self.grid.datagrid('load');
	};
	this.showChanges = function(){
		self.grid.datagrid('showChanges');
	}
	this.paginationOptions={layout:['list','sep','first','prev','sep','manual','sep','next','last','sep','refresh','info'],
			pageSize:25,
			pageList:[25,50,100],
		    onSelectPage:this.onSelectPage
	};
	this.grid=$('#'+options.grid_id);
	var isPagination=true;
	//if(options.pager_id){
		//this.grid.pager=$('#'+options.pager_id);
		//this.grid.pager.pagination(this.paginationOptions);
	this.grid.gridParam={"pageNumber":1,"pageSize":this.paginationOptions.pageSize};
	if(options.gridParam){
		$.extend(this.grid.gridParam,options.gridParam);
	}
	//}
	if(options.paging=="no"){
		//不分页
		this.grid.gridParam={"paging":"no"};
		isPagination=false;
	}
	this.gridOptions={
			idField:'id',//指定id字段
			sqlname:options.sqlname,
			toolbar:"#searchbar",
			fit:true,
		    singleSelect: true,//单选
			rownumbers:true,//显示序号
			pagination:isPagination,//显示分页
			columns:this.columns,//定义显示列
			onSortColumn:this.onSortColumn,//点击排序按钮触发函数
			onClickRow:this.onDblClickRow,
			onDblClickRow:this.onDblClickRow,//双击行触发函数
			//selectOnCheck:false,//点击复选框是否选中该行
			//checkOnSelect:false,//点击行时是否选中复选框
			multiSort:true//是否启用多列排序
	};
	if(options.isToolbar=="no"){
		delete this.gridOptions.toolbar;
	}else{
		if(options.toolbar_id){
			this.gridOptions.toolbar="#"+options.toolbar_id;
		}
	}
	if(options.rownumbers!=undefined){
		this.gridOptions.rownumbers=options.rownumbers;
	}
	if(options.singleSelect!=undefined){
		this.gridOptions.singleSelect=options.singleSelect;
	}
	if(options.rowedit!=undefined&&!options.rowedit){
		delete this.gridOptions.onDblClickRow;
	}
	if(options.idField!=undefined){
		this.gridOptions.idField=options.idField;
	}
	this.onClickRow=function(rowIndex, rowData){
		//单击事件
		if(options.onClickRow){
			options.onClickRow(rowIndex, rowData);
		}
	}
	
	if(options.onLoadSuccess){
		this.gridOptions.onLoadSuccess=options.onLoadSuccess;
	}
	if(options.afterEditing){
		this.gridOptions.afterEditing=options.afterEditing;
	}
	this.gridOptions.loadurl=options.loadurl||("/authenticated/grid/"+options.sqlname);
	this.gridOptions.saveurl=options.saveurl||("/authenticated/grid/update/"+options.sqlname);
	this.initColumnUrl=options.initColumnUrl||"/authenticated/grid/column/v2/"+options.page_id;
	this.initColumn=function(){
		$.ajax({
			type: "post",
			contentType:"application/json",
			async:false,
			url:self.initColumnUrl,
			success:function(result){
				if(result.success){
					var gridColumn=result.data.column;
					if(gridColumn){
						self.comboboxDatas=result.data.combo_data;
						$.each(gridColumn,function(i,v){
							var column_name=v.column_name;
							var column={field:column_name,title:v.column_display_name};
							if(v.is_hidden=="yes"){
								column.hidden=true;
							}
							if(v.is_order=="yes"){
								column.sortable=true;
							}
							var edit_type=v.edit_column_type;
							if(edit_type=="combobox"){
								column.formatter=new self.fun.field.formatter(column_name).comboboxFormatter;
								if(v.is_edit_column=="yes"){
									column.editor={
											type:'combobox',
											options:{
												panelHeight:'auto',
												panelMaxHeight:200,
												editable:false,
												valueField:'code_value',
												textField:'code_name',
												data: self.comboboxDatas[column_name]
											}
										};
								}
							}else if(edit_type=="combotree"){
								var newArray=transformCombotreeArray(self.comboboxDatas[column_name]);
								self.combotreeDatas[column_name]=newArray;
								column.formatter=new self.fun.field.formatter(column_name).combotreeFormatter;
								if(v.is_edit_column=="yes"){
									column.editor={
											type:'combotree',
											options:{
												data:newArray
											}
										};
								}
							}else if(edit_type=="datetimebox"){
								if(v.is_edit_column=="yes"){
									column.editor={
											type:'datetimebox',
											options:{
												//showSeconds:false
											}
										};
								}else{}
							}else if(edit_type=="datebox"){
								if(v.is_edit_column=="yes"){
									column.editor={
											type:'datebox',
											options:{
											}
										};
								}else{}
							}else if(edit_type=="image"){
								column.formatter=function(value,row,index){
				            	    
					  				return "<img style=\"height:100px;width:100px;\"  src=\""+value+"\" />";
							  	}
							}else if(edit_type=="integer"){
								if(v.is_edit_column=="yes"){
									column.editor={
											type:'numberbox',options:{}
										};
								}
							}else if(edit_type=="decimal"){
								if(v.is_edit_column=="yes"){
									column.editor={
											type:'numberbox',options:{precision:2}
										};
								}
							}else{
								if(v.is_edit_column=="yes"){
									column.editor={
											type:'textbox',options:{}
										};
								}
							}
							if(v.width&&v.width>0){
								column.width=v.width;
							}
							self.columns[0].push(column);
						});
						
					}
				}else{
					$.messager.alert("提示", "初始化表格失败："+result.message);
				}
			}
		})
		
	}
	if(options.columns){
		this.columns=options.columns;
		this.gridOptions.columns=options.columns;
	}else{
		this.initColumn();
	}
	this.grid.datagrid(this.gridOptions);
	this.grid.pager=this.grid.datagrid('getPager');
	this.grid.pager.pagination(this.paginationOptions);
	if(options.autoload==undefined||options.autoload){
		this.grid.datagrid("load");
	}
	$(document).keydown(function(event){
		if(event.keyCode == 13){
			self.load();
		}
	});
}
